package com.wehealth;



import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.umeng.analytics.MobclickAgent;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;

@SuppressLint("ResourceAsColor")
public class Report extends Fragment {
	
	
	private MainActivity context;
	private ImageView reportView;
	private static  String JSONResult;
	private int[] mProgress = new int[7];
	private int mIconWidth;
	private int mIconHeight;
	
	public  Report()
	{
		Log.i("init:", "Report"); 
	}
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		return  inflater.inflate(R.layout.report, null);
	}

	public void onActivityCreated(Bundle savedInstanceState){
		
		super.onActivityCreated(savedInstanceState);
		
		MainActivity activity = (MainActivity)getActivity();
		 context = activity;

	    MobclickAgent.openActivityDurationTrack(false);
	        
			//SIMMON_ADD
			new Thread(){
				@Override
				public void run(){
					try {
						getPlanData();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				handler.sendEmptyMessage(0);
				}
		}.start();
		 
		 
		 reportView = (ImageView)activity.findViewById(R.id.temp_report);

		
		//返回主页按钮-------------------------------------------------------//
		 Button bBack = (Button) activity.findViewById(R.id.bBack_report);
			
		 bBack.setOnClickListener(new View.OnClickListener()
			{
				public void onClick(View v)
				{
					
				    context.switchContentHome();
					
				}
			});
			
		//------------------------------------------------------------------//
		 
	}
	
	
    private Bitmap makeReportBitmapIcon(Drawable bgDrawable) {
    	
    	 mIconWidth = reportView.getWidth();
    	 mIconHeight = reportView.getHeight();
    	Log.d("SIMMON","mIconHeight="+mIconHeight);
    	Log.d("SIMMON","mIconWidth = "+mIconWidth);
        Bitmap b = Bitmap.createBitmap(Math.max(mIconWidth, 1),
                Math.max(mIconHeight, 1),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(b);
        canvas.drawColor(Color.WHITE);
        bgDrawable.setBounds(0, 0, b.getWidth(), b.getHeight());
        bgDrawable.draw(canvas);

        
        PaintDrawPath(canvas); 
 
        return b;
    }
    
    
    private void PaintDrawPath(Canvas canvas){
        Paint paint = new Paint();
        paint.setColor(Color.RED);
        paint.setStrokeWidth(5);
        
        float startX,startY;
        startX = (float) (mIconWidth*32/155.0);
        startY = (float) (mIconHeight * (23.5/142));
        float mgapX = (float) (mIconWidth *16.5/155.0);
        float mgapY = (float) (mIconHeight * 9.5/142);
        
        float[] x = new float[7];
        float[] y = new float[7];
        
        for(int i = 0; i < 7;i++){
        	x[i] = startX+mgapX*i;
        }
        for(int j =0 ; j<7;j++){	
        	float length = (float) (mProgress[j]/100.0);
        	y[j] = startY +(float) (1-(float) (mProgress[j]/100.0)) * mgapY*7;

        }
        
        for(int n=0;n<6;n++){  
        canvas.drawLine(x[n], y[n],x[n+1], y[n+1], paint);
        }

    }
    
    
    /**
	 * 渲染界面,显示数据
	 */
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message paramMessage) {
			super.handleMessage(paramMessage);
			
			if(JSONResult!=null){
			    BindWeekData(JSONResult);
			    JSONResult =null;
			}else{
			    //context.openMainActivityDialog(); 
			}
	
			Drawable mbg = reportView.getDrawable();
			Bitmap reportIcon =makeReportBitmapIcon(mbg);
			reportView.setImageBitmap(reportIcon);
		}
	};

	private void BindWeekData(String strJSON){
	    
		try{
				 JSONObject jsonObject = new JSONObject(strJSON);
				 String weekData = jsonObject.getString("result");
			     String[] weekDataArray = weekData.split(",");
			        for (int i = 0; i < weekDataArray.length; i++) {
			        	//mProgress[i] =Integer.parseInt(weekDataArray[i]);
			        }
			        mProgress[0] = 0;
			        mProgress[1] = 100;
			        mProgress[2] = 30;
			        mProgress[3] = 100;
			        mProgress[4] = 0;
			        mProgress[5] = 70;
			        mProgress[6] = 90;
				  
    }
    catch(JSONException ex)
    {
    		Log.e("JSON Error: ", ex.toString()); 
    }
		
	}
	
	
	private void  getPlanData() throws IOException
	{
		//http://www.552120.com/API/Plan_GetHealthSum.aspx?userID=1&amp;planID=3
		String userID = "1";
		String planID = "3";
	
		String httpUrl = com.wehealth.util.GetUrl.Plan_GetHealthSum();
		 HttpPost httpRequest= new HttpPost(httpUrl);
		 
		 List <NameValuePair> params = new ArrayList <NameValuePair>();
		 
		 params.add(new BasicNameValuePair("userID",userID));
		 params.add(new BasicNameValuePair("planID",planID)); 
		 try
		 {
			 httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
			
			 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
			 
			 if(httpResponse.getStatusLine().getStatusCode() == 200)
			 {
				 JSONResult = EntityUtils.toString(httpResponse.getEntity());
			 }
		 }
		 catch(Exception e)
		 {
			
			 Log.e("error:",  e.toString());
			 
		 }

	}
	
	
    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        MobclickAgent.onPageEnd("Report"); 
    }


    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        MobclickAgent.onPageStart("Report"); 
    }

}
